<?php 
/**
 * $ModDesc
 * 
 * @version		$Id: helper.php $Revision
 * @package		modules
 * @subpackage	mod_lofslidenews
 * @copyright	Copyright (C) JAN 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved.
 * @website 	htt://landofcoder.com
 * @license		GNU General Public License version 2
 */
// no direct access
defined('_JEXEC') or die;

require_once JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php';
if( !defined('PhpThumbFactoryLoaded') ) {
	require_once dirname(__FILE__).DS.'libs'.DS.'phpthumb/ThumbLib.inc.php';
	define('PhpThumbFactoryLoaded',1);
}

abstract class modLofK2SlideShowHelper {
	/**
	 * @var static string $regex;
	 */
	static $regex = "#<img.+src\s*=\s*\"([^\"]*)\"[^\>]*\>#iU";	
	
	/**
	 * get list k2 items
	 */
	public static function getList( $params ){
		$tmppath =  JPATH_SITE.DS.'cache'.DS.'lofthumbs'.DS;
		if( !file_exists($tmppath) ) {
			JFolder::create( $tmppath, 0755 );
		}
		// if the cache option is enabed ?
		if ( $params->get('enable_cache') ) {
			$cache =& JFactory::getCache( 'mod_lofk2slideshow' );
			$cache->setCaching( true );
			$cache->setLifeTime( $params->get( 'cache_time', 30 ) * 60 );	
			return $cache->get( array(  'modLofK2SlideShowHelper' , '_getList' ), array( $params ) ); 
		} else {
			return self::_getList( $params );
		}		
	}
	
	/**
	 * check K2 Existed ?
	 */
	public static function isK2Existed(){
		return is_file( JPATH_SITE.DS.  "components" . DS . "com_k2" . DS . "k2.php" );	
	}
	
	/**
	 * get the list of k2 items
	 * 
	 * @param JParameter $params;
	 * @return Array
	 */
	public static function _getList( $params ){
		global $mainframe;
		$maxTitle  	   = $params->get( 'max_title', '100' );
		$maxDesciption = $params->get( 'max_description', 100 );
		$openTarget    = $params->get( 'open_target', 'parent' );
		$formatter     = $params->get( 'style_displaying', 'title' );
		$titleMaxChars = $params->get( 'title_max_chars', '100' );
		$descriptionMaxChars = $params->get( 'description_max_chars', 100 );
		$condition     = self::buildConditionQuery( $params );
		$isThumb       = $params->get( 'auto_renderthumb',1);
		$ordering      = $params->get( 'ordering', 'created_asc');
		$limit 	       = $params->get( 'limit_items', 4 );
		$ordering      = str_replace( '_', '  ', $ordering );
		$my 	       = &JFactory::getUser();
		$aid	       = $my->get( 'aid', 0 );
		$thumbWidth    = (int)$params->get( 'thumbnail_width', 35 );
		$thumbHeight   = (int)$params->get( 'thumbnail_height', 60 );
		$imageHeight   = (int)$params->get( 'main_height', 300 ) ;
		$imageWidth    = (int)$params->get( 'main_width', 660 ) ;
		$excludeIds    = $params->get( 'exclude_article_ids', '' );
		$overrideLinks = array();
		$user = &JFactory::getUser();
		$aid = $user->get('aid');
		$db = &JFactory::getDBO();
		
		
		if( $tmp = $params->get('override_links', '' ) ){
				$tmp = is_array($tmp)?$tmp:array($tmp);
				foreach( $tmp as $titem ){
					$link  = explode("@", $titem );	
					if( count($link) > 1 ){
						$overrideLinks[(int)trim(strtolower($link[0]))]=$link[1];
					}
				}
			}
		$jnow = &JFactory::getDate();
		$now = $jnow->toMySQL();
		$nullDate = $db->getNullDate();
		
		require_once ( JPath::clean(JPATH_SITE.'/components/com_k2/helpers/route.php') );
		$query = "SELECT a.*, cr.rating_sum/cr.rating_count as rating, c.name as categoryname,
						c.id as categoryid, c.alias as categoryalias, c.params as categoryparams, cc.commentcount as commentcount".
				" FROM #__k2_items as a".
					" LEFT JOIN #__k2_categories c ON c.id = a.catid" .
					" LEFT JOIN #__k2_rating as cr ON a.id = cr.itemid".
					" LEFT JOIN (select cm.itemid  as id, count(cm.id) as commentcount from #__k2_comments as cm
																where cm.published=1 group by cm.itemid) as cc on a.id = cc.id";
			
		$query .= " WHERE a.published = 1"
					. " AND a.access <= {$aid}"
					. " AND a.trash = 0"
					. " AND c.published = 1"
					. " AND c.access <= {$aid}"
					. " AND c.trash = 0 " ;	
					

		$query .= " AND ( a.publish_up = ".$db->Quote($nullDate)." OR a.publish_up <= ".$db->Quote($now)." )";
		$query .= " AND ( a.publish_down = ".$db->Quote($nullDate)." OR a.publish_down >= ".$db->Quote($now)." )";
			
			
		if( $params->get('featured_items_show','0') == 0 ){
			$query.= " AND a.featured != 1";
		} elseif(  $params->get('featured_items_show','0') == 2 ) {
			$query.= " AND a.featured = 1";
		}
		
		$query .=  $condition . ' ORDER BY ' . $ordering;	
		$query .=  $limit ? ' LIMIT ' . $limit : '';
		$db->setQuery($query);
		$data = $db->loadObjectlist();

		if( empty($data) ) return array();
		
		foreach( $data as $key => &$item ){	
			
			if($item->access <= $aid ) {
				$item->link = JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.$item->alias, $item->catid.':'.$item->categoryalias));
			} else {
				$item->link = JRoute::_('index.php?option=com_user&view=login');
			}
			
			if( array_key_exists($item->id,$overrideLinks) ){
				$data[$key]->link=$overrideLinks[$item->id];
			}
			$item->catlink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($item->catid.':'.urlencode($item->categoryalias))));
			$item->category_title = $item->categoryname;
			$item->date = JHtml::_('date', $item->created, JText::_('DATE_FORMAT_LC2')); 
			
			$item->subtitle = self::substring( $item->title, $titleMaxChars );
			$item->description = self::substring( $item->introtext,
																$descriptionMaxChars );
																
			self::lookUpImages( $item );
			if( $item->mainImage &&  $image=self::renderThumb($item->mainImage, $imageWidth, $imageHeight, $item->title, $isThumb ) ){
				$item->mainImage = $image;
			}
			$item->rating = (is_numeric($item->rating))?floatval($item->rating / 5 * 100):null;
			if( $item->thumbnail &&  $image = self::renderThumb($item->thumbnail, $thumbWidth, $thumbHeight, $item->title, $isThumb ) ){
				$item->thumbnail = $image;
			}
		}
		
		return $data;	
	}
	
	/**
	 * looking for image inside the media folder.
	 */
	public static function lookingForK2Image( &$item, $size='XL' ){
		//Image
		$item->imageK2Image='';
		if (JFile::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_'.$size.'.jpg'))
			$item->imageK2Image = JURI::root().'media/k2/items/cache/'.md5("Image".$item->id).'_'.$size.'.jpg';
		return $item; 
	}
	
	/**
	 * build condition query base parameter  
	 * 
	 * @param JParameter $params;
	 * @return string.
	 */
	public static  function buildConditionQuery( $params ){
		$source = trim($params->get( 'source', 'k2category' ) );
		if( $source == 'k2category' ){
			$catids = $params->get( 'category','');
			
			if( !$catids ){
				return '';
			}
			$catids = !is_array($catids) ? $catids : '"'.implode('","',$catids).'"';
			$condition = ' AND  a.catid IN( '.$catids.' )';
		} else {
			$ids = preg_split('/,/',$params->get( 'article_ids',''));	
			$tmp = array();
			foreach( $ids as $id ){
				$tmp[] = (int) trim($id);
			}
			$condition = " AND a.id IN('". implode( "','", $tmp ) ."')";
		}
		return $condition;
	}
	
	/**
	 * parser a custom tag in the content of article to get the image setting.
	 * 
	 * @param string $text
	 * @return array if maching.
	 */
	public static function parserCustomTag( $text ){ 
		if( preg_match("#{lofimg(.*)}#s", $text, $matches, PREG_OFFSET_CAPTURE) ){ 
			return $matches;
		}	
		return null;
	}
	
	/**
	 *  check the folder is existed, if not make a directory and set permission is 755
	 *
	 *
	 * @param array $path
	 * @access public,
	 * @return boolean.
	 */
	public static function makeDir( $path ){
		$folders = explode ( '/',  ( $path ) );
		$tmppath =  JPATH_SITE.DS.'images'.DS.'cache'.DS;
		if( !file_exists($tmppath) ) {
			JFolder::create( $tmppath, 0755 );
		}; 
		for( $i = 0; $i < count ( $folders ) - 1; $i ++) {
			if (! file_exists ( $tmppath . $folders [$i] ) && ! JFolder::create( $tmppath . $folders [$i], 0755) ) {
				return false;
			}	
			$tmppath = $tmppath . $folders [$i] . DS;
		}		
		return true;
	}
	
	/**
	 *  check the folder is existed, if not make a directory and set permission is 755
	 *
	 *
	 * @param array $path
	 * @access public,
	 * @return boolean.
	 */
	public static function renderThumb( $path, $width=100, $height=100, $title='', $isThumb=true ){
		
		if( !preg_match("/.jpg|.png|.gif/",strtolower($path)) ) return  $path;
			$path = str_replace( JURI::base(), '', $path );
			if( $isThumb ){
				$imagSource = JPATH_SITE.DS. str_replace( '/', DS,  $path );
				if( file_exists($imagSource)  ) {
					$tmp = explode("/",$path);
					$imageName = $tmp[count($tmp)-1];
					$path =  $width."x".$height."_".$imageName;
					$thumbPath = JPATH_SITE.DS.'cache'.DS.'lofthumbs'.DS. str_replace( '/', DS,  $path );
				
					if( !file_exists($thumbPath) ) {
						$thumb = PhpThumbFactory::create( $imagSource  );  	
						$thumb->adaptiveResize( $width, $height );
						$thumb->save( $thumbPath  );
					}
					$path = JURI::base()."cache/lofthumbs/".$path;
				} 
			}
		return '<img title="'.$title.'" height="'.$height.'"  src="'.$path.'"/>';
	}
	
	/**
	 * get parameters from configuration string.
	 *
	 * @param string $string;
	 * @return array.
	 */
	public static function parseParams( $string ) {
		$string = html_entity_decode($string, ENT_QUOTES);
		$regex = "/\s*([^=\s]+)\s*=\s*('([^']*)'|\"([^\"]*)\"|([^\s]*))/";
		 $params = null;
		 if(preg_match_all($regex, $string, $matches) ){
				for ($i=0;$i<count($matches[1]);$i++){ 
				  $key 	 = $matches[1][$i];
				  $value = $matches[3][$i]?$matches[3][$i]:($matches[4][$i]?$matches[4][$i]:$matches[5][$i]);
				  $params[$key] = $value;
				}
		  }
		  return $params;
	}
	
	/**
	 * parser a image in the content of article.
	 *
	 * @param poiter $row .
	 * @return void
	 */
	public static function lookUpImages( &$row ){
		$text =  $row->introtext.$row->fulltext;
		$data = self::parserCustomTag( $text );
		if( isset($data[1][0]) ){
			$tmp = self::parseParams( $data[1][0] );
			$row->mainImage = isset($tmp['src']) ? $tmp['src']:'';
			$row->thumbnail = $row->mainImage ;// isset($tmp['thumb']) ?$tmp['thumb']:'';	
		} else {
			$row  = self::lookingForK2Image( &$row );
			
			if( $row->imageK2Image != '' ){
				$row->thumbnail = $row->mainImage = $row->imageK2Image;	
				return $row;
			}
			preg_match ( self::$regex, $text, $matches); 
			$images = (count($matches)) ? $matches : array();
			if (count($images)){
				$row->mainImage = $images[1];
				$row->thumbnail = $images[1];
			} else {
				$row->thumbnail = '';
				$row->mainImage = '';	
			}
		}
	}
	
	/**
	 * load css - javascript file.
	 * 
	 * @param JParameter $params;
	 * @param JModule $module
	 * @return void.
	 */
	public static function loadMediaFiles( $params, $module ){
		// if the verion is equal 1.6.x
		$app = JFactory::getApplication();
		if( (float)$app->get ('MooToolsVersion')>='1.2' ) {
			JHTML::script(  'script_jl16x.js','modules/'.$module->module.'/assets/');
		} else {
			JHTML::script( 'script_jl15x.js','modules/'.$module->module.'/assets/');
		}
		JHTML::stylesheet( 'style.css','modules/'.$module->module.'/assets/' );	
	}
	
	/**
	 * get a subtring with the max length setting.
	 * 
	 * @param string $text;
	 * @param int $length limit characters showing;
	 * @param string $replacer;
	 * @return tring;
	 */
	public static function substring( $text, $length = 100, $replacer='...' ){
		$string = strip_tags( $text );
		return JString::strlen( $string ) > $length ? JString::substr( $string, 0, $length ).$replacer: $string;
	}
}
?>